#include "uartWorker.h"

uartWorker::uartWorker(ResultSettings &r, QObject *parent)
    : resultSettings(r), QObject(parent), serial(new QSerialPort(this)) {
    connect(serial, &QSerialPort::readyRead, this, &uartWorker::handleReadyRead);
    connect(serial, &QSerialPort::errorOccurred, this, [=](QSerialPort::SerialPortError err){
        if (err != QSerialPort::NoError)
            emit errorOccurred(serial->errorString());
    });
}

uartWorker::~uartWorker() {
    closeSerial();
}

void uartWorker::openSerial(const QString &portName, int baudRate) {
    if (serial->isOpen())
        serial->close();

    serial->setPortName(portName);
    serial->setBaudRate(baudRate);

    if (!serial->open(QIODevice::ReadWrite)) {
        emit errorOccurred("Open failed: " + serial->errorString());
    }
}

void uartWorker::closeSerial() {
    if (serial->isOpen())
        serial->close();
}

void uartWorker::writeData(const QByteArray &data) {
    //qDebug() << serial->isOpen();
    if (serial->isOpen()) {
        //qDebug() << "writeData:" << QString::fromUtf8(data);
        serial->write(data);
    }
}

void uartWorker::handleReadyRead() {
    QByteArray data = serial->readAll();
    emit dataReceived(data);
}

void uartWorker::processUart() {
    if (resultSettings.isHaveSpaker) {
        QByteArray data;
        data.append(static_cast<char>(0x01));  // 发送 01
        writeData(data);
    }
    if (resultSettings.isHavePassener) {
        QByteArray data;
        data.append(static_cast<char>(0x02));  // 发送 03
        writeData(data);
    }
    if (resultSettings.isHaveIntruder) {
        QByteArray data;
        data.append(static_cast<char>(0x03));  // 发送 02
        writeData(data);
    }
}
